package jh.com.jhappbf.assay;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;
import jh.com.jhappbf.weight.query.SelectActivity;

public class AssayAdd2 extends AbActivity implements OnClickListener {
    private ImageView mSearchImg;
    private EditText mPlateNumber;
    private EditText mCargoName;

    private LinearLayout mInputLayout;
    private Button mBtnOk;
    private Button mRefreshOk;
    private static final int GET_PLATENUM_REQUEST_CODE = 0X0001;
    //	private String mSaverId="";
    private String mTarget = "";
    //	private String mNet = "0";
//	private String mBalance = "0";
    private String mCompute = "";
    private String mCargoname = "";
    private String mPlatenum = "";
    private LinkedHashMap<String, String> mTargetAlias = new LinkedHashMap<>();
    private LinkedHashMap<String, EditText> mTargetTxt = new LinkedHashMap<>();

    private EditText mAssayValue;
    private EditText mAssayWeight;
    private EditText mAssayAdvice;
    private EditText mAssayResult;
    private EditText mAssayDeduction;
    private AbLoadDialogFragment mDialogFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.assay_add_activity2);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.assay_add_title);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        try {
            mSearchImg = findViewById(R.id.assay_search_platenum);
            mSearchImg.setOnClickListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mAssayValue = findViewById(R.id.assay_value_edit);
        mAssayWeight = findViewById(R.id.assay_weight_rate_edit);
        mAssayAdvice = findViewById(R.id.assay_advice_edit);
        mAssayResult = findViewById(R.id.assay_result_edit);
        mAssayDeduction = findViewById(R.id.assay_weight_value_edit);

        mAssayValue.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("D".equals(mCompute)) {
                    mAssayWeight.setText(s);
                }
            }
        });
        mPlateNumber = findViewById(R.id.assay_search_edit);
        mCargoName = findViewById(R.id.assay_cargoname_edit);
        mInputLayout = findViewById(R.id.assay_input_layout);
        mBtnOk = findViewById(R.id.assay_btn_ok);
        mBtnOk.setOnClickListener(this);
        mRefreshOk = findViewById(R.id.assay_btn_refresh);
        mRefreshOk.setOnClickListener(this);
    }

    /**
     * 刷新
     */
    private void refreshInput() {
        mPlateNumber.setText("");
        mCargoName.setText("");
        mAssayValue.setText("");
        mAssayWeight.setText("");
        mAssayAdvice.setText("");
        mAssayResult.setText("");
        mAssayDeduction.setText("");

        for (Entry<String, EditText> entry : mTargetTxt.entrySet()) {
            entry.getValue().setText("");
        }
        mInputLayout.removeAllViews();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.assay_btn_ok:
                setAssay();
                break;
            case R.id.assay_btn_refresh:
                refreshInput();
                break;
            case R.id.assay_search_platenum:
                selectPlateNum();
                //	getFieldValue("platenumber",GET_PLATENUM_REQUEST_CODE);
                break;
            default:
                break;
        }
    }

    /**
     * 保存化验结果
     */
    private void setAssay() {
        String advice = String.valueOf(mAssayAdvice.getText());
        if (advice.length() == 0) {
            AbToastUtil.showToast(this, "质量意见不能为空!");
            return;
        }
        String assayResult = String.valueOf(mAssayResult.getText());
        if (assayResult.length() == 0) {
            AbToastUtil.showToast(this, "化验结果不能为空!");
            return;
        }
        mDialogFragment = AbDialogUtil.showLoadDialog(AssayAdd2.this,
                R.mipmap.ic_load, "添加中,请稍等...");
        mDialogFragment.setCancelable(false);

        StringBuilder builder = new StringBuilder();
        builder.append("A@").append(mAssayValue.getText());
        builder.append("#");
        builder.append("R@").append(mAssayResult.getText());
        builder.append("#");
        builder.append("S@").append(mAssayWeight.getText());
        builder.append("#");
        builder.append("备注@").append(mAssayAdvice.getText());
        builder.append("#");
        for (Entry<String, EditText> entry : mTargetTxt.entrySet()) {
            builder.append(entry.getKey());
            builder.append("@");
            builder.append(entry.getValue().getText());
            builder.append("#");
        }
        String assayTable = builder.toString();

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("A", mAssayValue.getText().toString());
        map.put("ducationRate", mAssayWeight.getText().toString());
        map.put("ducationWeight", mAssayDeduction.getText().toString());
        map.put("S8", mAssayAdvice.getText().toString());
        map.put("S10", mAssayResult.getText().toString());
        StringBuilder builderSaver = new StringBuilder();
        for (Entry<String, String> entry : map.entrySet()) {
            builderSaver.append(entry.getKey());
            builderSaver.append("@");
            builderSaver.append(entry.getValue());
            builderSaver.append("#");
        }

        String saverTable = builderSaver.toString();

        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        String methodName = "AddAssay";
        param.add("platenumStr");
        param.add("cargonameStr");
        param.add("assayContent");
        param.add("saverContent");
        param.add("user");

        value.add(mPlatenum);
        value.add(mCargoname);
        value.add(assayTable);
        value.add(saverTable);
        value.add(State.mName);

        Listener<String> listener = response -> {

            AbDialogUtil.removeDialog(AssayAdd2.this);
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String result = obj.optString("result");
                if (result.equals("true")) {
                    refreshInput();
                }
                String memo = obj.optString("memo");
                AbToastUtil.showToast(AssayAdd2.this, memo);
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(AssayAdd2.this);
            AbToastUtil.showToast(AssayAdd2.this, "添加失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(webService);
    }

    /**
     * 选择车号
     */
    private void selectPlateNum() {
        Intent i = new Intent(AssayAdd2.this, AssayPlatenumSelect.class);
        //	Intent i = new Intent(AssayAdd2.this,SelectActivity.class);

        startActivityForResult(i, GET_PLATENUM_REQUEST_CODE);
    }


    /**
     * 获取字段值
     */
    private void getFieldValue(String field, int value) {
        Intent i = new Intent(AssayAdd2.this, SelectActivity.class);
        i.putExtra("flag", field);
        startActivityForResult(i, value);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == GET_PLATENUM_REQUEST_CODE) {
//				mSaverId = data.getStringExtra("id");
                mPlatenum = data.getStringExtra("result");
                mPlateNumber.setText(mPlatenum);


//				mCargoname = data.getStringExtra("cargoname");
//				mTarget = data.getStringExtra("target");
//				mNet = data.getStringExtra("net");
                //if(mNet.length() == 0) mNet = "0";
//				mBalance = data.getStringExtra("balance");
                //if(mBalance.length() ==0) mBalance="0";
//				mCompute = data.getStringExtra("compute");
//				mPlateNumber.setText(mPlatenum);
//				mCargoName.setText(mCargoname);
//				makeView(mTarget);
            }
        }
    }

    private void makeView(String target) {
        if (target.length() == 0) {
            return;
        }
        mTargetAlias.clear();
        mTargetTxt.clear();
        String[] arr = target.split("#");
        for (String item : arr) {
            String[] arr1 = item.split("@");
            if (arr1.length > 1) {
                if (!mTargetAlias.keySet().contains(arr1[0]) && arr1[0].length() > 0 && arr1[1].length() > 0) {
                    if ("A".equals(arr1[0]) || "R".equals(arr1[0]) || "S".equals(arr1[0]) || "备注".equals(arr1[0])) {
                        continue;
                    }
                    mTargetAlias.put(arr1[0], arr1[1]);
                }
            }
        }


        Iterator iterator = mTargetAlias.entrySet().iterator();
        mInputLayout.removeAllViews();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = (Entry<String, String>) iterator.next();
            String key = entry.getKey();
            String value = entry.getValue();

            LinearLayout layout = new LinearLayout(AssayAdd2.this);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            int paddingValue = PixAndDpUtil.dp2px(2, AssayAdd2.this);
            layout.setPadding(paddingValue, paddingValue, paddingValue, paddingValue);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setLayoutParams(param);

            EditText edit = new EditText(AssayAdd2.this);
            edit.setHint("填写" + value);
            int editPadding = PixAndDpUtil.dp2px(8, AssayAdd2.this);
            edit.setPadding(editPadding, editPadding, editPadding, editPadding);
            layout.addView(edit);
            mInputLayout.addView(layout);
            mTargetTxt.put(key, edit);
        }
    }
}
